package com.kucai.yifaqapp.util;

import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.net.wifi.WifiManager;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Patterns;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.kucai.yifaqapp.global.App;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author zsy
 * @date 2018/3/8 17:09
 * 描述:  工具类
 */

public class Tool {
    private static Context context = App.getContext();
    private static Resources res = context.getResources();
    private static Pattern p = Pattern.compile("^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(18[0,5-9]))\\d{8}$");
    private static TextPaint textPaint = new TextPaint();
    private static float sNoncompatDensity;
    private static float sNoncompatScaledDensity;


    /**
     * 今日头条适配方案
     */
    public static void setCoustomDensity() {
        DisplayMetrics displayMetrics = res.getDisplayMetrics();
        if (sNoncompatDensity == 0) {
            sNoncompatDensity = displayMetrics.density;
            sNoncompatScaledDensity = displayMetrics.scaledDensity;
            context.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        sNoncompatScaledDensity = res.getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });

            float targetDensity = displayMetrics.widthPixels / 360;
            float targetScaledDensity = targetDensity * (sNoncompatScaledDensity / sNoncompatDensity);
            int targetDensityDpi = (int) (160 * targetDensity);

            displayMetrics.density = targetDensity;
            displayMetrics.scaledDensity = targetScaledDensity;
            displayMetrics.densityDpi = targetDensityDpi;
        }
    }


    /**
     * 像素转换为密度值
     */
    public static int pxToDp(float px) {
        final float scale = res.getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 密度转换为像素值
     */
    public static int dpToPx(float dp) {
        final float scale = res.getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }


    /**
     * 局中显示Toast
     *
     * @param content
     */
    public static void showToastCenter(@NonNull String content) {
        Toast toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 局中显示Toast
     *
     * @param content
     * @param view    自定义View
     */
    public static void showToastCenter(@NonNull String content, View view) {
        Toast toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 正常显示Toast
     *
     * @param content
     */
    public static void showToast(@NonNull String content) {
        Toast toast = Toast.makeText(context, content, 3);
        toast.show();
    }


    /**
     * 设置圆角，边框线及颜色，背景颜色
     *
     * @param view        控件
     * @param radiusDP    半径，单位dp
     * @param strokeDP    边框，单位dp
     * @param strokeColor 边框颜色，R.color
     * @param solidColor  填充色
     */
    public static void setRadiusShape(View view, int radiusDP, int strokeDP, @ColorRes int strokeColor, @ColorRes int solidColor) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(dpToPx(radiusDP));
        drawable.setStroke(dpToPx(strokeDP), res.getColor(strokeColor));
        drawable.setColor(res.getColor(solidColor));
        view.setBackgroundDrawable(drawable);
    }

    /**
     * 设置圆角，边框线及颜色
     *
     * @param view
     * @param radiusDP
     * @param strokeDP
     * @param strokeColor
     */
    public static void setRadiusShape(View view, float radiusDP, float strokeDP, @ColorRes int strokeColor) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(dpToPx(radiusDP));
        drawable.setStroke(dpToPx(strokeDP), res.getColor(strokeColor));
        view.setBackgroundDrawable(drawable);
    }

    /**
     * 设置圆角，背景色
     *
     * @param view
     * @param radiusDP
     * @param solidColor
     */
    public static void setRadiusShape(View view, float radiusDP, @ColorRes int solidColor) {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(dpToPx(radiusDP));
        drawable.setColor(res.getColor(solidColor));
        view.setBackgroundDrawable(drawable);
    }

    ///////////////////////////     注册判断     ////////////////////////////////////

    /**
     * 判断手机号码格式
     *
     * @param mobiles 手机号
     */
    public static boolean isMobile(String mobiles) {

        if (TextUtils.isEmpty(mobiles)) {
            showToastCenter("手机号不可为空!");
            return false;
        }

        Matcher m = p.matcher(mobiles);
        if (!m.matches()) {
            showToastCenter("手机号格式不正确");
            return false;
        }

        return true;
    }

    /**
     * 判断邮箱格式
     *
     * @param email
     */
    public static boolean isEmail(String email) {


        if (TextUtils.isEmpty(email)) {
            showToastCenter("邮箱不可为空!");
            return false;
        }


        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            showToastCenter("邮箱格式不正确");
            return false;
        }

        return true;

    }


    /**
     * 判断密码及确认密码
     *
     * @param password        密码
     * @param confirmPassword 确认密码
     */
    public static boolean isPassword(String password, String confirmPassword) {
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
            showToastCenter("密码或确认密码不可为空!");
            return false;
        }

        if (password.length() < 6) {
            showToastCenter("至少输入六位密码!");
            return false;
        }

        if (!password.equals(confirmPassword)) {
            showToastCenter("两次密码输入不一致!");
            return false;
        }

        return true;

    }

    public static boolean isEmpty(String content, String toastContent) {
        if (TextUtils.isEmpty(content)) {
            showToastCenter(toastContent);
            return false;
        }
        return true;
    }


    //////////////////////////////////////////////////////////////////////

    /**
     * 画圆角图片
     *
     * @param mBitmap
     * @param index
     * @return
     */
    public static Bitmap bimapRound(Bitmap mBitmap, float index) {
        Bitmap bitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_4444);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);

        //设置矩形大小
        Rect rect = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
        RectF rectf = new RectF(rect);

        // 相当于清屏
        canvas.drawARGB(0, 0, 0, 0);
        //画圆角
        canvas.drawRoundRect(rectf, index, index, paint);
        // 取两层绘制，显示上层
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        // 把原生的图片放到这个画布上，使之带有画布的效果
        canvas.drawBitmap(mBitmap, rect, rect, paint);
        return bitmap;
    }

    /**
     * 画纯圆角图片,适用于图片是正方形
     *
     * @param mBitmap
     * @return
     */
    public static Bitmap bimapRound(Bitmap mBitmap) {
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);

        //设置矩形大小
        Rect rect = new Rect(0, 0, width, height);
        RectF rectf = new RectF(rect);

        // 相当于清屏
        canvas.drawARGB(0, 0, 0, 0);
        //画圆角
        canvas.drawRoundRect(rectf, width / 2, height / 2, paint);
        // 取两层绘制，显示上层
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        // 把原生的图片放到这个画布上，使之带有画布的效果
        canvas.drawBitmap(mBitmap, rect, rect, paint);
        return bitmap;
    }

    /**
     * 获取指定文本宽度
     *
     * @param text 文本
     * @return 宽度
     */
    public static float getTextWidth(String text, float textSize) {
        textPaint.setTextSize(textSize);
        return textPaint.measureText(text);
    }

    /**
     * 获取当前系统时间，默认 yyyy年MM月dd日 HH:mm:ss
     *
     * @param simpleDateFormat
     * @return
     */
    public static String getCurSystemTime(SimpleDateFormat simpleDateFormat) {
        if (simpleDateFormat == null) {
            // HH:mm:ss
            simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        }
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }

    //////////////////////////////////////////////////////////////////////


    /**
     * 调用此方法输入所要转换的时间戳输入例如（1402733340）输出（"2014年06月14日16时09分00秒"）
     *
     * @param time
     * @return
     */
    public static String times(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        @SuppressWarnings("unused")
        long lcc = Long.valueOf(time);
        int i = Integer.parseInt(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;

    }


    /**
     * 获取版本名
     *
     * @return
     */
    public static String getVersionName() {
        return getPackageInfo().versionName;
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static int getVersionCode() {
        return getPackageInfo().versionCode;
    }

    /**
     * 通过PackageInfo得到的想要启动的应用的包名
     *
     * @return
     */
    public static PackageInfo getPackageInfo() {
        PackageInfo pInfo = null;

        try {
            //通过PackageManager可以得到PackageInfo
            PackageManager pManager = context.getPackageManager();
            pInfo = pManager.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return pInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pInfo;
    }

    /**
     * 获取登录设备mac地址
     *
     * @return Mac地址
     */
    public static String getMacAddress() {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        String mac = wm.getConnectionInfo().getMacAddress();
        return mac == null ? "" : mac;
    }

}
